// API服务配置
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 推荐相关API
export const recommendationAPI = {
  // 获取个性化推荐
  getRecommendations: (params) => {
    return api.post('/api/recommendations', params)
  },

  // 获取文本相似推荐
  getSimilarRecommendations: (params) => {
    return api.post('/api/recommendations/similar', params)
  },

  // 获取标签热门内容
  getHotContentByTag: (tagId, size = 20) => {
    return api.get(`/api/recommendations/hot/${tagId}`, {
      params: { size }
    })
  },

  // 记录用户行为
  recordBehavior: (contentId, behaviorType) => {
    return api.post('/api/recommendations/behavior', null, {
      params: {
        content_id: contentId,
        behavior_type: behaviorType
      }
    })
  },

  // 清除推荐缓存
  clearCache: () => {
    return api.delete('/api/recommendations/cache')
  },

  // 获取推荐统计
  getStats: () => {
    return api.get('/api/recommendations/stats')
  }
}

// 用户相关API
export const userAPI = {
  // 获取用户信息
  getUserInfo: () => {
    return api.get('/api/user/profile')
  },

  // 获取用户标签
  getUserTags: () => {
    return api.get('/api/user/tags')
  },

  // 设置用户标签
  setUserTags: (tagIds) => {
    return api.post('/api/user/tags', { tag_ids: tagIds })
  },

  // 更新用户信息
  updateUserInfo: (userData) => {
    return api.put('/api/user/profile', userData)
  }
}

// 认证相关API
export const authAPI = {
  // 发送验证码
  sendCode: (phone) => {
    return api.post('/api/auth/send-code', { phone })
  },

  // 验证码登录
  loginWithCode: (phone, code) => {
    return api.post('/api/auth/login-code', { phone, code })
  },

  // 密码登录
  loginWithPassword: (username, password) => {
    return api.post('/api/auth/login-password', { username, password })
  },

  // 注册
  register: (userData) => {
    return api.post('/api/auth/register', userData)
  },

  // 退出登录
  logout: () => {
    return api.post('/api/auth/logout')
  }
}

// 标签相关API
export const tagAPI = {
  // 获取所有标签
  getAllTags: () => {
    return api.get('/api/tags')
  },
  
  // 获取所有标签（别名）
  getTags: () => {
    return api.get('/api/tags')
  },

  // 获取标签详情
  getTagDetail: (tagId) => {
    return api.get(`/api/tags/${tagId}`)
  }
}

// 内容相关API
export const contentAPI = {
  // 获取内容列表
  getContentList: (params) => {
    return api.get('/api/content/list', { params })
  },

  // 获取我发布的内容
  getMyContent: (params) => {
    return api.get('/api/content/my', { params })
  },

  // 获取内容详情
  getContentDetail: (contentId) => {
    return api.get(`/api/content/${contentId}`)
  },

  // 发布内容
  publishContent: (contentData) => {
    return api.post('/api/content', contentData)
  },

  // 更新内容
  updateContent: (contentId, contentData) => {
    return api.put(`/api/content/${contentId}`, contentData)
  },

  // 删除内容
  deleteContent: (contentId) => {
    return api.delete(`/api/content/${contentId}`)
  }
}

// 导出默认API实例
export default api
